package com.banmoon.collection;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 简单的生产者消费者模式
 */
public class Demo5 {

    public static void main(String[] args) {
        MyDemo5 myDemo4 = new MyDemo5();
        new Thread(() -> {
            for(int i = 0; i < 10; i++) myDemo4.increment();
        }, "线程A").start();
        new Thread(() -> {
            for(int i = 0; i < 10; i++) myDemo4.decrement();
        }, "线程B").start();
        new Thread(() -> {
            for(int i = 0; i < 10; i++) myDemo4.increment();
        }, "线程C").start();
        new Thread(() -> {
            for(int i = 0; i < 10; i++) myDemo4.decrement();
        }, "线程D").start();

    }

}

class MyDemo5{

    private int number = 0;

    private ReentrantLock lock = new ReentrantLock();

    /**
     * 通过
     */
    Condition condition = lock.newCondition();

    public void increment(){
        lock.lock();
        try {
            while (number==1)
                condition.await();
            number++;
            System.out.println(Thread.currentThread().getName() + "：" + number);
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void decrement(){
        lock.lock();
        try {
            while (number==0)
                condition.await();
            number--;
            System.out.println(Thread.currentThread().getName() + "：" + number);
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

}
